package middlerware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"micro/common"
	"net/http"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(context *gin.Context) {
		tokenStr := context.GetHeader("Authorization")
		if tokenStr == "" || tokenStr[0:7] != "Bearer " {
			//如果token有问题，回传失败
			context.JSON(http.StatusUnauthorized, gin.H{
				"message": "用户验证失败",
			})
			context.Abort()
			return
		}

		token, claims, err := common.ParseToken(tokenStr[7:])
		if err != nil || !token.Valid {
			// 回传错误
			context.JSON(http.StatusUnauthorized, gin.H{
				"message": "用户验证失败",
			})
			fmt.Println("parse token error: ", err)
			context.Abort()
			return
		}

		//验证成功了，上下文中加入 username，然后继续往后走
		context.Set("user", claims.Username)
		context.Next()

	}
}
